#!/usr/bin/python

import json
import sys
import re
import time

#Read taskwarrior data file
def readJSONfile(path, appendId=False):
    result = []
    ident = 1
    try:
        with open(path, 'r') as f:
            for line in f.readlines():
                #Fix into proper json format
                parsedLine = readJSONline(line)
                if appendId:
                    parsedLine["ID"] = ident
                    ident = ident + 1
                if parsedLine:
                    result.append((parsedLine, determineClass(parsedLine)))
    except:
        sys.stderr.write("Reading of \"" + path + "\" failed.\n")
        sys.exit(1)

    return result

#Read a line from the taskwarrior data file and fix JSON format
def readJSONline(line):

    line = line.strip()
    if re.match(r'^$', line):
        return None
    line = re.sub(r'^\[', "{", line)
    line = re.sub(r'\]$', "}", line)
    line = re.sub(r'([\w]*):("[^"]*")', r'"\1":\2', line)
    line = re.sub(r'("[^"]*":"[^"]*") ("[^"]*":"[^"]*")', r'\1,\2', line)
    line = re.sub(r'("[^"]*":"[^"]*") ("[^"]*":"[^"]*")', r'\1,\2', line)

    return json.loads(line)

def determineClass(parsedLine):
    clas = ""
    if "due" in parsedLine:
        if time.gmtime() > time.gmtime(long(parsedLine["due"])):
            clas = "Late"

    if "status" in parsedLine:
        if parsedLine["status"] == "deleted":
            clas = "Deleted"
        elif parsedLine["status"] == "completed":
            clas = clas + "Completed"
        elif "start" in parsedLine:
            clas = clas + "Start"

    if clas == "":
        clas = "normal"
    return clas

def readUndoFile(path):
    result = []
    try:
        with open(path, 'r') as f:
            record = {}
            for line in f:
                if line.strip() == "---":
                    result.append(record)
                    record = {}
                else:
                    ret = parseUndoRecord(line)
                    record[ret[0]] = ret[1]
    except:
        sys.stderr.write("Reading of \"" + path + "\" failed.\n")
        sys.exit(1)

    return result

def parseUndoRecord(line):
    if (re.match(r'^time [\d]*$', line)):
        time = line[5:].strip()
        return ("time", time)

    elif (re.match(r'^old \[.*\]$', line)):
        old = line[4:].strip()
        return ("old", readJSONline(old))

    elif (re.match(r'^new \[.*\]$', line)):
        new = line[4:].strip()
        return ("new", readJSONline(new))
